<template>
	<view :class="['content', !BusinesImgList.length ? 'busines' : '']">
		<u-sticky v-if="BusinesImgList.length">
			<swiper class="content-swiper" indicator-dots indicator-active-color="#21b3c6">
				<swiper-item class="content-swiper-item" v-for="(item, index) in BusinesImgList" :key="index">
					<img class="content-swiper-item-image" :src="item" alt="" />
				</swiper-item>
			</swiper>
		</u-sticky>

		<view class="content-card">
			<view class="title">
				{{TicketDetails.Name || ''}}
			</view>
			<u-cell :border="false" title="选择日期:">
				<view slot="label" @click="handleCalendarShow(false)">
					<u-input v-model="orderForm.Date" placeholder="选择日期" readonly></u-input>
				</view>
			</u-cell>
			<u-cell :border="false" title="选择时间:">
				<view slot="label" @click="pickerShow = true">
					<u-input v-model="orderForm.TimeTips" placeholder="选择时间"  readonly></u-input>
				</view>
			</u-cell>
		</view>
		<view class="content-card" style="margin-top: 20rpx;">
			<view class="title">其它信息</view>
			<view class="content-card-price">
				单价/人：
				<b v-if="TicketDetails.ShowPrice">￥{{TicketDetails.ShowPrice}}</b>
				<b class="MarketPrice" v-if="TicketDetails.MarketPrice">￥{{TicketDetails.MarketPrice}}</b>
			</view>
			<view class="content-card-count">
				<view class="label">
					选择数量
				</view>
				<view class="value">
					<u-number-box v-model="TicketCount" class="number-box">
						<view slot="minus" class="number-btn">
							<img class="image" src="http://mihuagu.jxwenxin.com/weixin/wxh5/images/9-1.png" alt="" />
						</view>
						<view slot="plus" class="number-btn">
							<img class="image" src="http://mihuagu.jxwenxin.com/weixin/wxh5/images/9-2.png" alt="" />
						</view>
					</u-number-box>
				</view>
			</view>

			<view class="content-card-family">
				<view class="tips">
					<text class="label">游客信息</text>
					<text class="count">至少填写1位</text>
					<text>游客信息</text>
				</view>
				<view class="family">
					<view
						:class="['family-item', familyActive(item) ]"
						v-for="(item, index) in FamilyList" :key="item.Id"
						@click="handleFamilyItem(item)"
					>
						{{item.Name}}
					</view>
					<view class="family-add" @click="familyAdd = true">
						<u-icon name="plus" size="40rpx"></u-icon>
					</view>
				</view>
				<view class="family-list">
					<view class="family-list-item" v-for="(item, index) in orderForm.UsersList" :key="item.Id">
						<view class="user-options">
							<view>游客</view>
							<view class="delete" @click="handleFamilyItem(item)">
								<u-icon name="close-circle" size="40rpx"></u-icon>
							</view>
						</view>
						<view class="user-content">
							<view>{{item.Name}}</view>
							<view>电话号: {{item.Mobile}}</view>
							<view>身份证 {{item.CardNo}}</view>
						</view>
						<view class="user-edit" @click="handleEditFamily(item)">
							编辑
						</view>
					</view>
				</view>
			</view>
		</view>

		<view class="content-card" style="margin-top: 20rpx;">
			<u-parse :content="TicketDetails.OrdersSubstance"></u-parse>
		</view>

		<view class="content-bottom">
			<view class="total-price">
				总价 <b>￥{{TotalPrice}}</b>
			</view>
			<view class="submit" @click="handleOrderSubmit">提交</view>
		</view>
		<!-- 时间区间 -->
		<u-picker
			:show="pickerShow"
			:columns="TimeColumns"
			@cancel="pickerShow = false"
			keyName="label"
			@confirm="handlePickerConfirm"
		></u-picker>
		<!-- 日历 -->
		<u-calendar
			className="ticket-calendar"
			:showTitle="false"
			round
			color="#30cfda"
			@confirm="handleCalendarShow"
			:monthNum="2"
			:show="calendarShow"
			:formatter="handleCalendarFormatter"
			@close="calendarShow = false"
		></u-calendar>
		<!-- 家人编辑 -->
		<family-popup :show.sync="familyAdd" :userData.sync="userActive" @userClose="handleEditClose" :familyList.sync="orderForm.UsersList"></family-popup>
	</view>
</template>

<script>
import * as api from '@/api';
import { getGoodsDetail, getUsersContactsList, getTicketCalendar, getTimeSharingByTicket, addEleCouponOrders  } from '@/api/mall.js'
import { dateFtt, getEveryDayDateByBetweenDate } from '@/utils/tools.js'
import dayjs from '@/uni_modules/uview-ui/libs/util/dayjs.js'
import FamilyPopup from '../components/FamilyPopup/index.vue';
//	日期价格区间
let datePriceList = [];
export default {
	components: { FamilyPopup },
	data () {
		return {
			pickerShow: false,
			calendarShow: false,
			familyAdd: false,
			TicketId: '',	//	票务Id
			TicketDetails: {},	//	票务详情
			userActive: null,
			orderForm: {
				ProdcutSpecId: 0,
				Date: '',
				TimeTips: '',
				Time: '',
				UsersList: [],	//	用户集合
				TicketSceneTimeId: 0,
				ProgramType: 0,
				OrderSource: 0,
				Total: 0,
				FieldValueList: []
			},
			TimeColumns: [],	//	时间价格list
			TicketCount: 1,
			FamilyList: [],
		}
	},
	watch: {
		orderForm: {
			handler(data){
				const { UsersList } = data || {}
				if (UsersList.length > this.TicketCount) {
					this.TicketCount = UsersList.length || 1;
				}
			},
			deep: true
		}
	},
	onLoad(options) {
		const { id } = options || {}
		if (id) {
			this.TicketId = id;
			this.getTicketDetails();
		}
	},
	computed: {
		BusinesImgList() {
			const { ImgList } =  this.TicketDetails || {};
			if (ImgList && ImgList.includes('|')) {
				return ImgList.split('|')
			}
			return ImgList || []
		},
		//	日期Id
		TicketSeason() {
			const { Date: date } = this.orderForm || {};
			if (!datePriceList.length) return 0;
			const datePriceIndex = datePriceList.findIndex(v => {
				const { Year, Month, Day } = v || {};
				return new Date(`${Year}-${Month}-${Day} 00:00:00`).getTime() === new Date(`${date} 00:00:00`).getTime()
			})
			return datePriceIndex !== -1 ? datePriceList[datePriceIndex] :{};
		},
		// 总价
		TotalPrice () {
			const { ShowPrice } = this.TicketDetails || {};
			return (this.TicketCount * ShowPrice).toFixed(2)
		}
	},
	methods: {
		// 日历渲染
		handleCalendarFormatter(day) {
			const dayDate = dayjs(day.date).format('YYYY-MM-DD')
			const calendarRange = datePriceList.filter(v => dayjs(v.PriceDate + ' 23:59:59').format() >= dayjs().format())
			day.disabled = true;
			if (calendarRange.length) {
				const range = calendarRange.filter(item => dayDate === item.PriceDate) || []
				if (!range || !range.length) return day;
				const  { TotalNum, Price}  = range[0] || {}
				day.bottomInfo = `¥${Price || 0}`;
				if (TotalNum) {
					day.dot = false;
					day.disabled = false;
				} else {
					day.dot = true;
					day.disabled = true;
				}
			}
			return day;
		},
		// 成员得选中class
		familyActive(item) {
			const { UsersList } = this.orderForm || {UsersList: []};
			const userIndex = UsersList.findIndex(v => v && v.Id === item.Id);
			return userIndex !== -1 ? 'active' : '';
		},
		// 增删成员
		handleFamilyItem(item) {
			const { UsersList } = this.orderForm || {UsersList: []};
			const userIndex = UsersList.findIndex(v => v && v.Id === item.Id);
			if (userIndex !== -1) {
				UsersList.splice(userIndex, 1)
				return;
			};
			UsersList.push(item);
		},
		// 编辑成员
		handleEditFamily(item) {
			this.userActive = item || {}
		},
		handleCalendarShow(type) {
			if (Array.isArray(type)) {
				const { Id } = datePriceList.filter(v => v.PriceDate === type[0])[0]
				this.orderForm.Date = type[0];
				this.calendarShow = false;
				this.getTimeSharingByTicket(Id);
				return;
			}
			if (!type) {
				this.calendarShow = true;
				return;
			}
		},
		handlePickerConfirm(data) {
			const { value } = data || {};
			if (Array.isArray(value)) {
				const { label, StarTime, EndTime, BalanceNum } = value[0] || {}
				this.orderForm.Time = `${StarTime} - ${EndTime}`;
				this.orderForm.Total = BalanceNum
				this.orderForm.TimeTips = label
				this.pickerShow = false;
				return;
			}
		},
		// 获取订单详情
		getTicketDetails() {
			const params = {
				Id: this.TicketId,
				IsLoadExtensionData: 1,
				OrderDate: ""
			}
			getGoodsDetail(params).then(res => {
				const {	Data } = res || {};
				const { Subtitle } = Data || {}
				this.TicketDetails = Data || {};
				Subtitle && uni.setNavigationBarTitle({
					title: Subtitle
				})
				this.getDiscount()
			}).catch(err => {
				uni.showToast({
					icon: 'none',
					title: '获取详情失败'
				})
			});
			this.getUsersFamily();
		},
		getDiscount () {
			const { ProductSpecList } = this.TicketDetails || {}

			if (!ProductSpecList || !ProductSpecList.length) return
			ProductSpecList.forEach(item => {
				const { StartDate, EndDate } = item || {};
				if (!StartDate || !EndDate) return item
				getEveryDayDateByBetweenDate(dayjs(StartDate).format('YYYY-MM-DD'), dayjs(EndDate).format('YYYY-MM-DD')).forEach(timeItem => {
					datePriceList.push({
						...item,
						PriceDate: timeItem,
					})
				})
			})
			if (!datePriceList && !datePriceList.length) return;
			// 去重
			let list = [];
			datePriceList = datePriceList.filter((item) => !list.includes(item.PriceDate) && list.push(item.PriceDate))
			const nowDate =  datePriceList.filter(item => item.PriceDate === dayjs().format('YYYY-MM-DD')) || []

			const { PriceDate, Id } = nowDate.length ? nowDate[0] : {}

			this.orderForm.Date = dayjs(PriceDate).format('YYYY-MM-DD')

			this.$nextTick(() => {
				this.getTimeSharingByTicket(Id);
			})
		},
		// 获取家人列表
		getUsersFamily() {
			getUsersContactsList({Index: 1, Size: 100}).then(res => {
				const { ErrorCode, Data } = res || {}
				if (ErrorCode == 0) {
					this.FamilyList = Data || []
				}
			})
		},
		getTimeSharingByTicket(ProdcutSpecId) {
			const { Date } = this.orderForm || {};
			const { TicketSeasonTimeId } = this.TicketSeason || {}
			this.orderForm.ProdcutSpecId = ProdcutSpecId
			const params = {
				ProdcutId: this.TicketId,
				ProdcutSpecId: ProdcutSpecId,
				OrderDate: this.orderForm.Date
			}
			getTicketCalendar(params).then(res => {
				const { Data } = res || {}
				const { TicketSceneTimeList } = Data || {};
				const TimeColumns = TicketSceneTimeList && TicketSceneTimeList.length && TicketSceneTimeList.map(item => {
					const { EndTime, StartTime, BalanceNum } = item || {};
					return {
						label: `${StartTime}-${EndTime}`, //	 (余票: ${BalanceNum})
						...item
					}
				}) || []
				this.TimeColumns = [TimeColumns];
				this.handlePickerConfirm({value: [TimeColumns[0]]})
			})
		},
		//	订单提交
		handleOrderSubmit() {
			const { UsersList, Date, ProdcutSpecId } = this.orderForm || {}
			if (!UsersList.length) {
				uni.showToast({
					title: '至少填写1位游客',
					icon: 'none'
				});
				this.familyAdd = true;
				return;
			}
			const userFamily = [...UsersList]
			if (this.TicketCount > UsersList.length) {
				const diff = this.TicketCount - UsersList.length;
				for(let i = 0; i < diff; i++) {
					userFamily.push(UsersList[0])
				}
			}
			const { BusinessId, Subtitle, Id } = this.TicketDetails || {}
			const params = {
				OrderProductList: [
					{
						BusinessId,
						ProductId: Id,
						ProductSpecId: ProdcutSpecId,
						SelfOrLogs: '',
						RoomCount: 0,
						OrderStartDate: Date,
						OrderEndDate: '',
						ProductName: Subtitle,
						Count: this.TicketCount,
						Persons: userFamily.map(item => {
							const { Mobile, CardNo, Name, IDCard, IdCard} = item || {}
							return {
								Mobile,
								Name,
								IDCard: IDCard || CardNo || IdCard
							}
						})
					},
				],
				Coupons: []
			}
			console.log(this.orderForm, '===orderForm', userFamily, params)
			addEleCouponOrders(params).then(res => {
				const { ErrorCode, Data, Msg } = res || {}
				if (ErrorCode == '0') {
					const { WxJsApiParam, IsNeedWxPay, OrdersId } = Data || {};
					const param = typeof WxJsApiParam === 'string' ? JSON.parse(WxJsApiParam) : WxJsApiParam || {};

					console.log('===WxJsApiParam', param)
					uni.requestPayment({
					    provider: 'wxpay',
						timeStamp: param.timeStamp,
						nonceStr: param.nonceStr,
						package: param.package,
						signType:param.signType,
						paySign: param.paySign,
						success: function (res) {
							uni.reLaunch({
								url: '/subpages/order/order'
							})
						},
						fail: function (err) {
							console.log('fail:' + JSON.stringify(err));
						}
					});
					return;
				}
				uni.showToast({
					title: Msg || '订单提交失败',
					icon: 'none'
				});
			})
		},
		//	修改关闭
		handleEditClose(data) {
			this.userActive = null;
			!data && this.getUsersFamily();
		}
	}
}
</script>

<style lang="scss" scoped>
.content{
	background-image: url('https://mihuagu.jxwenxin.com/weixin/wxh5/images/bgc11.jpg');
	background-repeat: no-repeat;
	background-size: 100% 100%;
	min-height: 100vh;
	padding: 380rpx 20rpx 120rpx;
	padding-bottom: calc(var(--status-bar-height) + 120rpx);
	box-sizing: border-box;
	&.busines{
		padding-top: 20rpx;
	}
	*{
		box-sizing: inherit;
	}
	&-swiper{
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		height: 340rpx;
		padding: 6rpx 16rpx;
		background: #fff;
		&-item {
			&-image{
				border-radius: 10rpx;
				width: 100%;
				height: 100%;
			}
		}
	}
	&-card{
		padding: 30rpx;
		width: 100%;
		height: 100%;
		border-radius: 20rpx;
		background: #fff;
		.title{
			color: #333333;
			font-size: 36rpx;
			font-weight: 600;
			margin-bottom: 20rpx;
			padding-bottom: 40rpx;
			line-height: 40rpx;
			border-bottom: 1px dashed rgba(0, 0, 0, .1);
		}
		&-label{
			font-size: 28rpx;
			color: #333;
			font-weight: 600;

		}
		&-price{
			display: flex;
			font-size: 32rpx;
			color: #333333;
			font-weight: 600;
			b{
				color: #e77843;
				&.MarketPrice{
					margin-left: 10rpx;
					color: rgb(204, 204, 204);
					text-decoration: line-through;
				}
			}
		}
		&-count{
			display: flex;
			align-items: center;
			font-size: 32rpx;
			color: #333333;
			font-weight: 600;

			.label{
				flex: 1;
			}
			.value{
				.number-btn{
					width: 80rpx;
					height: 80rpx;
					position: relative;
					top: 8rpx;
					.image{
						width: inherit;
						height: inherit;
					}
				}
			}
		}
		&-family{
			border-top: 1px dashed #e6ebf1;
			margin-top: 20rpx;
			padding: 20rpx 0;
			.tips{
				text{
					font-size: 30rpx;
					color: #666666;
					margin-right: 8rpx;
					&.label{
						font-size: 32rpx;
						color: #333;
					}
					&.count{
						color: #ff7a45;
					}
				}
			}
			.family{
				width: 100%;
				display: flex;
				flex-wrap: wrap;
				padding:10rpx 0 20rpx;
				border-bottom: 2rpx solid #e6ebf1;
				&-item{
					border: 2rpx solid #e6ebf1;
					color: #717d9d;
					line-height: 78rpx;
					height: 78rpx;
					text-align: center;
					width: 188rpx;
					border-radius: 10rpx;
					margin-right: 20rpx;
					margin-top: 10rpx;
					&.active{
						border-color: #30CFDA;
					}
				}
				&-add{
					border: 2rpx solid #e6ebf1;
					width: 78rpx;
					line-height: 78rpx;
					height: 78rpx;
					text-align: center;
					margin-top: 10rpx;
					font-size: 40rpx;
					display: flex;
					align-items: center;
					justify-content: center;
				}
			}
			.family-list{
				&-item{
					display: flex;
					padding: 20rpx 10rpx;
					border-bottom: 1px solid #e6ebf1;
					box-sizing: border-box;
					.user-options{
						width: 160rpx;
						height: 160rpx;
						padding: 40rpx 0;
						box-sizing: border-box;
						view{
							color: #333;
							font-size: 26rpx;
							text-align: center;
							&.delete{
								margin-top: 20rpx;
								display: flex;
								justify-content: center;
								.u-icon{
									justify-content: center !important;
								}
							}
						}
					}
					.user-content{
						width: calc(100% - 260rpx);
						height: 160rpx;
						display: flex;
						flex-direction: column;
						justify-content: space-between;
						view{
							color: #333;
							font-size: 26rpx;
						}
					}
					.user-edit{
						width: 100rpx;
						height: 160rpx;
						color: #30cfda;
						font-size: 30rpx;
						line-height: 160rpx;
						text-align: center;
					}
				}
			}
		}
	}
	&-bottom{
		width: 100%;
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		background: #fff;
		z-index: 9;
		.total-price{
			box-sizing: content-box;
			flex: 1;
			height: calc(var(--status-bar-height) + 100rpx);
			line-height: calc(var(--status-bar-height) + 100rpx);
			color: #e77843;
			font-size: 30rpx;
			display: flex;
			justify-content: center;
			b{
				font-size: 40rpx;
				font-weight: 600;
			}
		}
		.submit{
			box-sizing: content-box;
			height: calc(var(--status-bar-height) + 100rpx);
			line-height: calc(var(--status-bar-height) + 100rpx);
			background-color: #30cfda;
			font-size: 36rpx;
			width: 250rpx;
			color: #fff;
			text-align: center;
		}
	}
}
</style>

<style lang="scss">
.ticket-calendar{
	.u-calendar-month__days__day__select__dot{
		width: 100% !important;
		line-height: 26rpx;
		height: 26rpx !important;
		top: 0 !important;
		text-align: center;
		right: 0 !important;
		background: transparent !important;
		&::before{
			content: '售罄';
			font-size: 20rpx;
			color: rgb(204, 204, 204);
		}
	}
	.u-calendar-month__days__day__select__buttom-info{
		color: red !important;
		font-size: 24rpx !important;
		height: 30rpx !important;
		bottom: 4rpx !important;
		line-height: 30rpx !important;
		padding-top: 6rpx;
	}
}
.content-card-count{
	.u-number-box{
		align-items: top !important;
	}
}
</style>
